<template>
  <div>
    <a-form-model size="small">
      <a-row :gutter="24">
        <a-col :lg="5" :md="12" :sm="24" v-if="actionType == 'areaAnalysis'">
          <a-form-model-item v-bind="formItemLayout" label="区域">
            <a-select allowClear optionFilterProp="children" v-model="queryParam.areaType">
              <a-select-option :value="1">全国</a-select-option>
              <a-select-option :value="2">全省</a-select-option>
              <a-select-option :value="3">全市</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :lg="5" :md="12" :sm="24" v-if="actionType == 'trendAnalysis' || actionType == 'diagnosticAnalysis'">
          <a-form-item v-bind="formItemLayout" label="年份">
            <a-select v-model="queryParam.year">
              <a-select-option v-for="(item, index) in years" :value="item" :key="index">{{ item }} </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form-model>
    <div>
      <div id="sexAnalysis" v-show="actionType == 'sexAnalysis'" class="chartDiv"></div>
      <div id="areaAnalysis" v-show="actionType == 'areaAnalysis'" class="chartDiv"></div>
      <div id="trendAnalysis" v-show="actionType == 'trendAnalysis'" class="chartDiv"></div>
      <div id="diagnosticAnalysis" v-show="actionType == 'diagnosticAnalysis'" class="chartDiv"></div>
      <div id="declareSubsidyAnalysis" v-show="actionType == 'declareSubsidyAnalysis'" class="chartDiv"></div>
    </div>
  </div>
</template>

<script>
import { deleteChildrenIfNull } from '@/utils/util'
import { sexAnalysis, areaAnalysis, trendAnalysis, diagnosisTypeAnalysis, declareSubsidyAnalysis } from '@/api/analysis'
import echarts from 'echarts'

export default {
  props: {
    actionType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      queryParam: {
        areaType: 1,
        year: 2021
      },
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      },
      Dept: [],
      DWLBDrop: [],
      ZJDrop: [],
      XLDrop: [],
      RYZTDrop: [],

      ageData: [],
      sexData: [],
      areaData: [],
      trendData: [],
      diagnosticAnalysisData: [],
      declareSubsidyAnalysisData: [],
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        }
      },
      map: {},
      chart1: null, // 创建一个chart变量
      chart2: null, // 创建一个chart变量
      chart3: null, // 创建一个chart变量
      chart4: null, // 创建一个chart变量
      chart5: null,
      option1: null,
      option2: null,
      option3: null,
      option4: null,
      option5: null,

      areaType: 1,
      years: [],
      year: null
    }
  },
  mounted() {
    //this.initChart()
  },
  watch: {
    queryParam: {
      handler(newValue, oldValue) {
        this.getData()
        setTimeout(() => {
          this.changeEchartData()
        }, 500)
      },
      deep: true
    }
  },
  created() {
    this.year = new Date().getFullYear()
    this.getYears()
    this.getData()
    setTimeout(() => {
      this.initChart()
    }, 1000)
    // setTimeout(() => {
    //   this.init()
    // }, 500)
  },
  methods: {
    getYears() {
      var year = new Date().getFullYear()
      for (let i = 0; i < 5; i++) {
        this.years.push(year - i)
      }
    },
    changeEchartData() {
      switch (this.actionType) {
        case 'ageAnalysis':
          this.option1.xAxis[0].data = this.ageData.map(res => {
            return res.Age_Interval
          })
          this.option1.series[0].data = this.ageData.map(res => {
            return res.num
          })
          this.chart1.setOption(this.option1)
          break
        case 'sexAnalysis':
          // this.option2.series[0].data = this.sexData.map(res => {
          //   return { value: res.num, name: res.Sex_name }
          // })
          this.initChart()
          break
        case 'areaAnalysis':
          // this.option3.series[0].data = this.areaData.map(res => {
          //   return { value: res.num, name: res.Education_name }
          // })
          this.initChart()
          break
        case 'trendAnalysis':
          // this.option4.series[0].data = this.trendData.map(res => {
          //   return { value: res.num, name: res.Political_name }
          // })
          this.initChart()
          break
        default:
          break
      }
    },
    initChart() {
      var data = []
      var total = 0
      var target = new Map()
      switch (this.actionType) {
        case 'trendAnalysis':
          this.chart1 = echarts.init(document.getElementById('trendAnalysis'), 'light')

          this.option1 = {
            color: ['#3398DB'],
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                // 坐标轴指示器，坐标轴触发有效
                type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
              }
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: [
              {
                type: 'category',
                data: this.trendData.map(res => {
                  return res.MonthName
                }),
                axisTick: {
                  alignWithLabel: true
                }
              }
            ],
            yAxis: [
              {
                type: 'value',
                name: '人数',
                minInterval: 1
              }
            ],
            series: [
              {
                name: '人数',
                type: 'bar',
                barWidth: '60%',
                data: this.trendData.map(res => {
                  return res.Count
                })
              }
            ]
          }
          // 绘制图表
          this.chart1.setOption(this.option1)
          setTimeout(() => {
            window.onresize = function() {
              if (this.chart1) {
                this.chart1.resize()
              }
            }
          }, 500)
          break
        case 'sexAnalysis':
          //   data = this.sexData.map(res => {
          //     return { value: res.num, name: res.Sex_name }
          //   })
          data.push({ value: this.sexData.Man, name: '男' })
          data.push({ value: this.sexData.Woman, name: '女' })
          data.forEach(item => {
            total += item.value
            target.set(item.name, item.value)
          })
          this.chart2 = echarts.init(document.getElementById('sexAnalysis'), 'light')
          console.log(this.sexData)
          this.option2 = {
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b} : {c} ({d}%)'
            },
            legend: {
              orient: 'vertical',
              left: 'left',
              formatter: function(name) {
                const lists = []
                const num = target.get(name)
                const inum = (target.get(name) / total) * 100
                const vnum = inum ? parseFloat(inum).toFixed(2) : 0
                lists.push(`${name} ${num}-${vnum}%`)
                return lists
              }
            },
            series: [
              {
                name: '性别',
                type: 'pie',
                radius: '55%',
                center: ['50%', '60%'],
                data: data
                // emphasis: {
                //   itemStyle: {
                //     shadowBlur: 10,
                //     shadowOffsetX: 0,
                //     shadowColor: 'rgba(0, 0, 0, 0.5)'
                //   }
                // }
              }
            ]
          }
          // 绘制图表
          this.chart2.setOption(this.option2)
          setTimeout(() => {
            window.onresize = function() {
              if (this.chart2) {
                this.chart2.resize()
              }
            }
          }, 500)
          break
        case 'areaAnalysis':
          data = this.areaData.map(res => {
            return { value: res.Count, name: res.AreaName }
          })
          data.forEach(item => {
            total += item.value
            target.set(item.name, item.value)
          })

          this.chart3 = echarts.init(document.getElementById('areaAnalysis'), 'light')
          this.option3 = {
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b} : {c} ({d}%)'
            },
            legend: {
              orient: 'vertical',
              left: 'left',
              formatter: function(name) {
                const lists = []
                const num = target.get(name)
                const inum = (target.get(name) / total) * 100
                const vnum = inum ? parseFloat(inum).toFixed(2) : 0
                lists.push(`${name} ${num}-${vnum}%`)
                return lists
              }
            },
            series: [
              {
                name: '区域',
                type: 'pie',
                radius: '55%',
                center: ['50%', '60%'],
                data: data
                // emphasis: {
                //   itemStyle: {
                //     shadowBlur: 10,
                //     shadowOffsetX: 0,
                //     shadowColor: 'rgba(0, 0, 0, 0.5)'
                //   }
                // }
              }
            ]
          }
          // 绘制图表
          this.chart3.setOption(this.option3)
          setTimeout(() => {
            // window.onresize = function() {
            //   if (this.chart3) {
            //     this.chart3.resize()
            //   }
            // }
            window.addEventListener('resize', () => {
              this.chart3.resize()
            })
          }, 500)
          break
        case 'diagnosticAnalysis':
          //   data = this.sexData.map(res => {
          //     return { value: res.num, name: res.Sex_name }
          //   })
          data = this.diagnosticAnalysisData.map(res => {
            return { value: res.Count, name: res.DiagnosisTypeName }
          })
          data.forEach(item => {
            total += item.value
            target.set(item.name, item.value)
          })
          this.chart4 = echarts.init(document.getElementById('diagnosticAnalysis'), 'light')
          console.log(this.sexData)
          this.option4 = {
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b} : {c} ({d}%)'
            },
            legend: {
              orient: 'vertical',
              left: 'left',
              formatter: function(name) {
                const lists = []
                const num = target.get(name)
                const inum = (target.get(name) / total) * 100
                const vnum = inum ? parseFloat(inum).toFixed(2) : 0
                lists.push(`${name} ${num}-${vnum}%`)
                return lists
              }
            },
            series: [
              {
                name: '诊断类别',
                type: 'pie',
                radius: '55%',
                center: ['50%', '60%'],
                data: data
                // emphasis: {
                //   itemStyle: {
                //     shadowBlur: 10,
                //     shadowOffsetX: 0,
                //     shadowColor: 'rgba(0, 0, 0, 0.5)'
                //   }
                // }
              }
            ]
          }
          // 绘制图表
          this.chart4.setOption(this.option4)
          setTimeout(() => {
            window.onresize = function() {
              if (this.chart4) {
                this.chart4.resize()
              }
            }
          }, 500)
        case 'declareSubsidyAnalysis':
          data.push({ value: this.declareSubsidyAnalysisData.DeclareSubsidy, name: '已申报' })
          data.push({ value: this.declareSubsidyAnalysisData.NoDeclareSubsidy, name: '未申报' })
          data.forEach(item => {
            total += item.value
            target.set(item.name, item.value)
          })
          this.chart5 = echarts.init(document.getElementById('declareSubsidyAnalysis'), 'light')
          this.option5 = {
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b} : {c} ({d}%)'
            },
            legend: {
              orient: 'vertical',
              left: 'left',
              formatter: function(name) {
                const lists = []
                const num = target.get(name)
                const inum = (target.get(name) / total) * 100
                const vnum = inum ? parseFloat(inum).toFixed(2) : 0
                lists.push(`${name} ${num}-${vnum}%`)
                return lists
              }
            },
            series: [
              {
                name: '申报信息',
                type: 'pie',
                radius: '55%',
                center: ['50%', '60%'],
                data: data
                // emphasis: {
                //   itemStyle: {
                //     shadowBlur: 10,
                //     shadowOffsetX: 0,
                //     shadowColor: 'rgba(0, 0, 0, 0.5)'
                //   }
                // }
              }
            ]
          }
          // 绘制图表
          this.chart5.setOption(this.option5)
          setTimeout(() => {
            window.onresize = function() {
              if (this.chart5) {
                this.chart5.resize()
              }
            }
          }, 500)
        default:
          break
      }
    },
    getData() {
      switch (this.actionType) {
        case 'trendAnalysis':
          this.getTrend()
          break
        case 'sexAnalysis':
          this.getSex()
          break
        case 'areaAnalysis':
          this.getEducation()
          break
        case 'declareSubsidyAnalysis':
          this.getDeclareSubsidy()
          break
        case 'diagnosticAnalysis':
          this.getDiagnostic()
          break
        default:
          break
      }
    },
    getTrend() {
      trendAnalysis(this.queryParam).then(res => {
        if (res.success) {
          this.trendData = res.data
        } else {
          this.$message.error(res.message)
        }
      })
    },
    getSex() {
      sexAnalysis(this.queryParam).then(res => {
        if (res.success) {
          this.sexData = res.data
        } else {
          this.$message.error(res.message)
        }
      })
    },
    getEducation() {
      areaAnalysis(this.queryParam).then(res => {
        if (res.success) {
          this.areaData = res.data
        } else {
          this.$message.error(res.message)
        }
      })
    },
    getDeclareSubsidy() {
      declareSubsidyAnalysis(this.queryParam).then(res => {
        if (res.success) {
          this.declareSubsidyAnalysisData = res.data
        } else {
          this.$message.error(res.message)
        }
      })
    },
    getDiagnostic() {
      diagnosisTypeAnalysis(this.queryParam).then(res => {
        if (res.success) {
          this.diagnosticAnalysisData = res.data
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // createdMethod() {
    //   switch (this.actionType) {
    //     case 'ageAnalysis':
    //       this.init(this.ageData)
    //       break
    //     case 'sexAnalysis':
    //       this.init(this.sexData)
    //       break
    //     case 'trendAnalysis':
    //       this.init(this.trendData)
    //       break
    //     case 'areaAnalysis':
    //       this.init(this.areaData)
    //       break
    //     default:
    //       break
    //   }
    // },
    changeData(data) {
      switch (this.actionType) {
        case 'trendAnalysis':
          this.initTrendParams(this.chart1, this.ageData)
          break
        case 'sexAnalysis':
          this.initSexParams(this.chart2, this.sexData)
          break
        case 'areaAnalysis':
          this.initEducationParams(this.chart3, this.areaData)
          break
        default:
          break
      }
    },
    init() {
      let chart = null
      switch (this.actionType) {
        case 'trendAnalysis':
          chart = new Chart({
            container: 'ageAnalysis',
            autoFit: true,
            height: 500,
            padding: [50, 20, 50, 20]
          })
          console.log('测试', this.ageData)
          this.initTrendParams(chart, this.ageData)
          break

        case 'sexAnalysis':
          chart = new Chart({
            container: 'sexAnalysis',
            autoFit: true,
            height: 500,
            padding: [20, 30, 30, 20]
          })
          this.initSexParams(chart, this.sexData)

          break
        case 'areaAnalysis':
          chart = new Chart({
            container: 'areaAnalysis',
            autoFit: true,
            height: 500
          })
          this.initEducationParams(chart, this.areaData)
          break
        case 'diagnosticAnalysis':
          chart = new Chart({
            container: 'diagnosticAnalysis',
            autoFit: true,
            height: 500
          })
          this.initEducationParams(chart, this.areaData)
          break
        case 'areaAnalysis':
          chart = new Chart({
            container: 'areaAnalysis',
            autoFit: true,
            height: 500
          })
          this.initEducationParams(chart, this.areaData)
          break
        default:
          break
      }
    },
    initEducationParams(chart, data) {
      chart.clear() // 清理所有图形
      chart.coordinate('theta', {
        radius: 0.75
      })

      chart.data(data)

      chart.scale('num', {
        alias: '人数'
      })

      chart.tooltip({
        showTitle: false,
        showMarkers: false
      })

      chart
        .interval()
        .position('num')
        .color('Education_name')
        .label('num', {
          content: data => {
            return `${data.Education_name}`
          }
        })
        .adjust('stack')

      chart.interaction('element-active')
      this.chart3 = chart
      this.chart3.render()
    },
    initPoliticalParams(chart, data) {
      chart.clear() // 清理所有图形
      chart.coordinate('theta', {
        radius: 0.75
      })

      chart.data(data)

      chart.scale('num', {
        alias: '人数'
      })

      chart.tooltip({
        showTitle: false,
        showMarkers: false
      })

      chart
        .interval()
        .position('num')
        .color('Political_name')
        .label('num', {
          content: data => {
            return `${data.Political_name}`
          }
        })
        .adjust('stack')

      chart.interaction('element-active')
      this.chart4 = chart
      this.chart4.render()
    },
    initSexParams(chart, data) {
      chart.clear() // 清理所有图形
      chart.coordinate('theta', {
        radius: 0.8
      })

      chart.data(data)

      chart.tooltip({
        showTitle: false,
        showMarkers: false
      })
      chart
        .interval()
        .adjust('stack')
        .position('num')
        .color('Sex_name', ['#1890ff', '#f04864'])
        .label('num', {
          content: obj => {
            const group = new G.Group({})
            group.addShape({
              type: 'image',
              attrs: {
                x: 0,
                y: 0,
                width: 40,
                height: 50,
                img: obj.Sex_name === '男' ? 'https://gw.alipayobjects.com/zos/rmsportal/oeCxrAewtedMBYOETCln.png' : 'https://gw.alipayobjects.com/zos/rmsportal/mweUsJpBWucJRixSfWVP.png'
              }
            })

            group.addShape({
              type: 'text',
              attrs: {
                x: 20,
                y: 54,
                text: obj.Sex_name,
                textAlign: 'center',
                textBaseline: 'top',
                fill: obj.Sex_name === '男' ? '#1890ff' : '#f04864'
              }
            })
            return group
          }
        })

      chart.interaction('element-active')
      this.chart2 = chart
      this.chart2.render()
    },
    initTrendParams(chart, data) {
      chart.clear() // 清理所有图形
      chart.data(data)
      chart.scale('num', {
        alias: '人数'
      })
      chart.tooltip({
        showMarkers: false
      })
      chart.interval().position('Age_Interval*num')
      chart.interaction('element-active')
      // 添加文本标注
      // data.forEach(item => {
      //   chart.annotation().text({
      //     position: [item.Age_Interval, item.num],
      //     content: item.num,
      //     style: {
      //       textAlign: 'center'
      //     },
      //     offsetY: -30
      //   })
      // })
      this.chart1 = chart
      this.chart1.render()
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    removeChildrenIfNUll(data) {
      data.map(a => {
        if (a && a.children.length > 0) {
          this.removeChildrenIfNUll(a.children)
        } else {
          deleteChildrenIfNull(a)
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.tree-select-label {
  display: inline-block;
  height: 30px;
  font-size: 12px;
  vertical-align: bottom;
  text-align: center;
}
.tree-select-self-FX {
  display: inline-block;
  width: 200px;
}
.chartDiv {
  height: 500px;
  margin: 0 auto;
}
</style>
